package pandora.apps.d3mob.controller;

import java.util.ArrayList;

import pandora.apps.d3mob.view.King;
import pandora.apps.d3mob.view.KingMoveModifier;
import pandora.apps.d3mob.view.KingMoveProgressModifier;
import android.util.FloatMath;
import android.view.MotionEvent;
import com.e3roid.E3Scene;
import com.e3roid.drawable.Shape;
import com.e3roid.drawable.modifier.ShapeModifier;
import com.e3roid.drawable.modifier.function.Linear;
import com.e3roid.drawable.tmx.TMXLayer;


public class MainController extends Shape {
	
	public static final int PIXELS_PER_SECOND = 60;
	
	private ArrayList<TMXLayer> mapLayers;
	private TMXLayer collisionLayer;
	private E3Scene scene;
	private King king;
	private ShapeModifier lastKingModifier;

	public MainController(int xpos, int ypos, int width, int height) {
		super(xpos, ypos, width, height);
	}
	
	public void setLayers(ArrayList<TMXLayer> mapLayers) {
		this.mapLayers = mapLayers;
	}

	public void setCollisionLayer(TMXLayer layer) {
		this.collisionLayer = layer;
	}

	public void setScene(E3Scene scene) {
		this.scene = scene;
		this.scene.addEventListener(this);
	}

	@Override
	public boolean onSceneTouchEvent(E3Scene scene, MotionEvent me) {
		if (me.getAction() == MotionEvent.ACTION_DOWN) {
			int touchX = (int)me.getX();
			int touchY = (int)me.getY();
			moveKingTo(touchX, touchY);
		}
		return false;
	}

	public void setKing(King king) {
		this.king = king;		
	}
	
	public void moveKingTo(int posx, int posy) {
		int currentX = this.king.getRealX();
		int currentY = this.king.getRealY();
		int x = posx - currentX;
		int y = posy - currentY;
		int length = (int)(FloatMath.sqrt((int)Math.pow(x, 2) + (int)Math.pow(y, 2)));
		int duration = length*1000/PIXELS_PER_SECOND;
		KingMoveModifier kmm = new KingMoveModifier(currentX, currentX, posx, currentY, currentY, posy);
		kmm.setKing(king);
		kmm.setMapLayers(mapLayers);
		kmm.setScene(scene);
		kmm.setCollisionLayer(collisionLayer);
		KingMoveProgressModifier modifier = new KingMoveProgressModifier(king, kmm, duration, Linear.getInstance(), kmm.getDir());
		if (lastKingModifier == null) {
			lastKingModifier = modifier;
		} else {
			lastKingModifier.finish(king);
		}
		this.king.animate(kmm.getDir());
		this.king.addModifier(modifier);
		lastKingModifier = modifier;
		this.king.stop();
	}
}
